package cn.wowjoy.office.pm.view.viewodel;

import android.arch.lifecycle.MediatorLiveData;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;

import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.google.gson.Gson;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import cn.bingoogolapple.androidcommon.adapter.BGABindingRecyclerViewAdapter;
import cn.bingoogolapple.androidcommon.adapter.BGABindingViewHolder;
import cn.wowjoy.office.R;
import cn.wowjoy.office.baselivedata.appbase.LiveDataWrapper;
import cn.wowjoy.office.baselivedata.appbase.NewBaseViewModel;
import cn.wowjoy.office.baselivedata.appbase.NewMainApplication;
import cn.wowjoy.office.data.remote.ApiService;
import cn.wowjoy.office.data.remote.ResultDataParse;
import cn.wowjoy.office.data.remote.RxSchedulerTransformer;
import cn.wowjoy.office.data.response.StaffResponse;
import cn.wowjoy.office.databinding.ItemPmManagerRvBinding;
import cn.wowjoy.office.homepage.MenuHelper;
import cn.wowjoy.office.pm.data.PmManageCardInfo;
import cn.wowjoy.office.pm.data.PmManageResponse;
import cn.wowjoy.office.pm.db.PmListDao;
import cn.wowjoy.office.pm.db.PmListDetailDao;
import cn.wowjoy.office.pm.db.PmReportListDetailEntity;
import cn.wowjoy.office.pm.db.PmReportListEntity;
import cn.wowjoy.office.utils.PreferenceManager;
import io.reactivex.Observable;
import io.reactivex.ObservableEmitter;
import io.reactivex.ObservableOnSubscribe;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;
import io.reactivex.observers.DisposableObserver;

public class PmManagerViewModel extends NewBaseViewModel {
    private String status;
    public StaffResponse userInfo;
    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }
    @Inject
    public PmManagerViewModel(@NonNull NewMainApplication application) {
        super(application);
        alllinnerAdapter.setItemEventHandler(this);
        soonlinnerAdapter.setItemEventHandler(this);
        outlinnerAdapter.setItemEventHandler(this);
        wronglinnerAdapter.setItemEventHandler(this);
        userInfo = new Gson().fromJson(PreferenceManager.getInstance().getStuffInfo(), StaffResponse.class);
    }

    @Override
    public void onCreateViewModel() {

    }

    @Override
    public void loadData(boolean ref) {
        super.loadData(ref);
        getAllListInfo(ref,"",status);
    }
    //点击查看详情
    public void onItemClick(BGABindingViewHolder holder, PmManageResponse.Detail model) {
            getManagerCardInfo(model.getCardId());
    }
    @Inject
    ApiService apiService;
    //全部数据
    public  MediatorLiveData<LiveDataWrapper<PmManageResponse>> allData = new MediatorLiveData<>();
    //即将超期数据
    public  MediatorLiveData<LiveDataWrapper<PmManageResponse>> soonData = new MediatorLiveData<>();
    //超期数据
    public  MediatorLiveData<LiveDataWrapper<PmManageResponse>> outData = new MediatorLiveData<>();
    //即将超期数据
    public MediatorLiveData<LiveDataWrapper<PmManageResponse>> wrongData = new MediatorLiveData<>();

    //ALL的Task
    public ArrayList<PmManageResponse.Detail> all_list;
    public BGABindingRecyclerViewAdapter<PmManageResponse.Detail, ItemPmManagerRvBinding> alllinnerAdapter = new BGABindingRecyclerViewAdapter<>(R.layout.item_pm_manager_rv);
    public LRecyclerViewAdapter allAdapter = new LRecyclerViewAdapter(alllinnerAdapter);

    //即将超期
    public ArrayList<PmManageResponse.Detail> soon_list;
    public BGABindingRecyclerViewAdapter<PmManageResponse.Detail, ItemPmManagerRvBinding> soonlinnerAdapter = new BGABindingRecyclerViewAdapter<>(R.layout.item_pm_manager_rv);
    public LRecyclerViewAdapter soonAdapter = new LRecyclerViewAdapter(soonlinnerAdapter);

    //已超期
    public ArrayList<PmManageResponse.Detail> out_list;
    public BGABindingRecyclerViewAdapter<PmManageResponse.Detail, ItemPmManagerRvBinding> outlinnerAdapter = new BGABindingRecyclerViewAdapter<>(R.layout.item_pm_manager_rv);
    public LRecyclerViewAdapter outAdapter = new LRecyclerViewAdapter(outlinnerAdapter);

    //故障
    public ArrayList<PmManageResponse.Detail> wrong_list;
    public BGABindingRecyclerViewAdapter<PmManageResponse.Detail, ItemPmManagerRvBinding> wronglinnerAdapter = new BGABindingRecyclerViewAdapter<>(R.layout.item_pm_manager_rv);
    public LRecyclerViewAdapter wrongAdapter = new LRecyclerViewAdapter(wronglinnerAdapter);

    public void setPmManagerListData(boolean isRefresh,List<PmManageResponse.Detail> data,String pmStatus) {
        switch (pmStatus){
            case "82-1": //即将超期
                setData(isRefresh,soon_list,data,soonlinnerAdapter,soonAdapter);
                break;
            case "82-2"://已超期
                setData(isRefresh,out_list,data,outlinnerAdapter,outAdapter);
                break;
            case "82-4"://故障
                setData(isRefresh,wrong_list,data,wronglinnerAdapter,wrongAdapter);
                break;
                default:
                setData(isRefresh,all_list,data,alllinnerAdapter,allAdapter);
        }
    }
    private void setData(boolean isRefresh,ArrayList<PmManageResponse.Detail> all_list ,List<PmManageResponse.Detail> data,
                         BGABindingRecyclerViewAdapter<PmManageResponse.Detail, ItemPmManagerRvBinding> alllinnerAdapter,
                         LRecyclerViewAdapter allAdapter){
        switch (status) {
            case "82-1":
                if (isRefresh) {
                    if (null == soon_list)
                        soon_list = new ArrayList<>();
                    soon_list.clear();
                    soon_list.addAll(data);

                    soonlinnerAdapter.setData(soon_list);
                } else {
                    soonlinnerAdapter.addMoreData(data);
                }
               soonAdapter.removeFooterView();
                if (!isRefresh && (null == data || data.isEmpty() )){
                    LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
                    View view = inflater.inflate(R.layout.nodata_footview,null,false);
                    soonAdapter.addFooterView(view);
                }
                soonAdapter.notifyDataSetChanged();
                refreshComplete();
                break;
            case "82-2":
                if (isRefresh) {
                    if (null == out_list)
                        out_list = new ArrayList<>();
                    out_list.clear();
                    out_list.addAll(data);

                    outlinnerAdapter.setData(out_list);
                } else {
                    outlinnerAdapter.addMoreData(data);
                }
               outAdapter.removeFooterView();
                if (!isRefresh && (null == data || data.isEmpty() )){
                    LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
                    View view = inflater.inflate(R.layout.nodata_footview,null,false);
                    outAdapter.addFooterView(view);
                }
                outAdapter.notifyDataSetChanged();
                refreshComplete();
                break;
            case "82-4":
                if (isRefresh) {
                    if (null == wrong_list)
                        wrong_list = new ArrayList<>();
                    wrong_list.clear();
                    wrong_list.addAll(data);

                    wronglinnerAdapter.setData(wrong_list);
                } else {
                    wronglinnerAdapter.addMoreData(data);
                }
                wrongAdapter.removeFooterView();
                if (!isRefresh && (null == data || data.isEmpty() )){
                    LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
                    View view = inflater.inflate(R.layout.nodata_footview,null,false);
                    wrongAdapter.addFooterView(view);
                }
                wrongAdapter.notifyDataSetChanged();
                refreshComplete();
                break;
              default:
                  if (isRefresh) {
                      if (null == all_list)
                          all_list = new ArrayList<>();
                      all_list.clear();
                      all_list.addAll(data);

                      alllinnerAdapter.setData(all_list);
                  } else {
                      alllinnerAdapter.addMoreData(data);
                  }
                  allAdapter.removeFooterView();
                  if (!isRefresh && (null == data || data.isEmpty() )){
                      LayoutInflater inflater = LayoutInflater.from(getApplication().getApplicationContext());
                      View view = inflater.inflate(R.layout.nodata_footview,null,false);
                      allAdapter.addFooterView(view);
                  }
                  allAdapter.notifyDataSetChanged();
                  refreshComplete();
                break;
        }
    }


    //获取全部任务的List
    public void getAllListInfo(boolean isRefresh,String fuzzySearchForPda , String pmStatus){
        isRefreshOrLoadMore(isRefresh);
        allData.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getListPmCardData(fuzzySearchForPda,pmStatus,pageIndex * pageSize,pageSize, MenuHelper.getAuidS().get("zc_pm"))
                .flatMap(new ResultDataParse<PmManageResponse>())
                .compose(new RxSchedulerTransformer<PmManageResponse>())
                .subscribe(new Consumer<PmManageResponse>() {
                    @Override
                    public void accept(PmManageResponse taskListResponse) throws Exception {
                        setPmManagerListData(isRefresh,taskListResponse.getList(), pmStatus);
                        allData.setValue(LiveDataWrapper.success(taskListResponse));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        allData.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }
    @Inject
    PmListDetailDao mDetailDao;
    @Inject
    PmListDao mPmListDao;
    public  MediatorLiveData<LiveDataWrapper<PmManageCardInfo>> detail = new MediatorLiveData<>();
    //点击查看详情
    public void getManagerCardInfo(String id){
        detail.setValue(LiveDataWrapper.loading(null));
        Disposable disposable = apiService.getManagerCardInfo(id)
                .flatMap(new ResultDataParse<PmManageCardInfo>())
                .compose(new RxSchedulerTransformer<PmManageCardInfo>())
                .subscribe(new Consumer<PmManageCardInfo>() {
                    @Override
                    public void accept(PmManageCardInfo taskListResponse) throws Exception {
                        detail.setValue(LiveDataWrapper.success(taskListResponse));
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
                        detail.setValue(LiveDataWrapper.error(throwable,null));
                    }
                });
        addDisposable(disposable);
    }



    public MediatorLiveData<LiveDataWrapper< List<PmReportListDetailEntity>>> scan = new MediatorLiveData<>();
    public void queryByQrCode(String qrCode,String userName){
        scan.setValue(LiveDataWrapper.loading(null));
        Disposable observer = (Disposable) Observable.create(new ObservableOnSubscribe<List<PmReportListDetailEntity>>() {
            @Override
            public void subscribe(ObservableEmitter<List<PmReportListDetailEntity>> e) throws Exception {
                List<PmReportListEntity> entities= mPmListDao.searchData(qrCode,userName);
//                if(null == entities ){
//                    //说明数据库存在这条 要更新
//                    entities=new ArrayList<>();
//                }
                if(null != entities){
                    List<PmReportListDetailEntity> exist=  mDetailDao.queryExist(qrCode,userName);
                    e.onNext(exist);
                }else{
                    e.onNext(new ArrayList<PmReportListDetailEntity>());
                }

            }
        }).compose(new RxSchedulerTransformer<>())
                .subscribeWith(new DisposableObserver<List<PmReportListDetailEntity>>() {
                    @Override
                    public void onNext(List<PmReportListDetailEntity> o) {
                        scan.setValue(LiveDataWrapper.success(o));
                    }

                    @Override
                    public void onError(Throwable e) {
                        scan.setValue(LiveDataWrapper.error(e,null));
                    }

                    @Override
                    public void onComplete() {
                    }
                });
        addDisposable(observer);
    }
}
